package org.jdns.jfreechess.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundByteHandlerAdapter;

import org.jdns.jfreechess.timeseal.Timeseal;
import org.jdns.jfreechess.timeseal.TimesealedMessage;

public class TimesealNegotiationHandler extends ChannelInboundByteHandlerAdapter {
  
  // if this is true and we get an inboundBufferUpdated, then we are using timeseal
  private boolean negotiationComplete = false;

  @Override
  public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    TimesealedMessage message = Timeseal.decrypt(in.array());

    if (!negotiationComplete && (message == null || !message.getMessage().startsWith("TIMESTAMP|"))) {
      // client is not using timeseal, remove it
      NoTimesealHandler handler = new NoTimesealHandler();
      ctx.pipeline().replace(this, "noTimesealHandler", handler);
      handler.inboundBufferUpdated(ctx, in);
    } else {
      ctx.pipeline().replace(this, "timesealHandler", new TimesealHandler());
      ctx.fireInboundBufferUpdated();
    }
  }
}
